package com.tenglong.teacher.services.hdx;


import android.text.TextUtils;
import android.util.Log;

import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.services.FastJsonConverterFactory;
import com.tenglong.teacher.services.HttpLogger;
import com.tenglong.teacher.services.WebRestApi;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;


/**
 * 获取WebRestApi对象用于请求数据
 */
public class CreateRequestEntity {

    public static WebRestApi getWebService() {
        return createRequest();
    }
    public static WebRestApi getWebServiceLogin() {
        return createRequestLogin();
    }
    public static WebRestApi getWebServiceUrl(String baseUrl) {
        return createRequestUrl(baseUrl);
    }
    private static String baseUrl;
    private static String appToken;
    private static String appId;
    private static WebRestApi restApi;

    private synchronized static WebRestApi createRequestLogin() {
        return getRetrofitLogin(IpUtils.Ips[0]);
    }
    private synchronized static WebRestApi createRequestUrl(String baseUrl) {
        return getRetrofitLogin(baseUrl);
    }
    private synchronized static WebRestApi createRequest() {
        if (DataState.getInstance().isLoginState()) {
            return getApi();
        } else {
            if (TextUtils.isEmpty(baseUrl)) {
                baseUrl = IpUtils.Ips[IpUtils.IpIndex];
                appToken = null;
                appId = null;
                restApi = getRetrofit();
                return restApi;
            } else {
                if (!baseUrl.equals(IpUtils.Ips[IpUtils.IpIndex])) {
                    baseUrl = IpUtils.Ips[IpUtils.IpIndex];
                    appToken = null;
                    appId = null;
                    restApi = getRetrofit();
                    return restApi;
                } else {
                    if (TextUtils.isEmpty(appToken) && TextUtils.isEmpty(appId)) {
                        if (restApi == null) {
                            restApi = getRetrofit();
                        }
                        return restApi;
                    } else {
                        appToken = null;
                        appId = null;
                        restApi = getRetrofit();
                        return restApi;
                    }
                }
            }
        }
    }
    private static WebRestApi getApi() {
        ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = userInfo.getUrl();
            if (TextUtils.isEmpty(baseUrl)){
                if (TextUtils.isEmpty(appToken)||TextUtils.isEmpty(appId)||!userInfo.getToken().equals(appToken)||!userInfo.getId().equals(appId)){
                    appToken = userInfo.getToken();
                    appId = userInfo.getId();
                    restApi = getRetrofit();
                    return restApi;
                } else {
                    if (restApi == null){
                        restApi = getRetrofit();
                    }
                    return restApi;
                }
            } else {
                appToken = userInfo.getToken();
                appId = userInfo.getId();
                restApi = getRetrofit();
                return restApi;
            }
        } else {
            if (baseUrl.equals(IpUtils.Ips[IpUtils.IpIndex]) || !baseUrl.equals(userInfo.getUrl()==null?"":userInfo.getUrl())) {
                baseUrl = userInfo.getUrl();
                appToken = userInfo.getToken();
                appId = userInfo.getId();
                restApi = getRetrofit();
                return restApi;
            } else {
                if (TextUtils.isEmpty(appToken) || TextUtils.isEmpty(appId)
                        || !appId.equals(userInfo.getId()) || !appToken.equals(userInfo.getToken())) {
                    appToken = userInfo.getToken();
                    appId = userInfo.getId();
                    restApi = getRetrofit();
                    return restApi;
                } else {
                    if (restApi == null) {
                        restApi = getRetrofit();
                    }
                    return restApi;
                }
            }
        }
    }

    private static WebRestApi getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(baseUrl == null ? IpUtils.Ips[IpUtils.IpIndex] :
                        (baseUrl.startsWith("http") || baseUrl.startsWith("https") ? baseUrl : IpUtils.Ips[IpUtils.IpIndex]))
                .client(getHttpClient())
                .addConverterFactory(FastJsonConverterFactory.create())
                .build().create(WebRestApi.class);
    }
    private static WebRestApi getRetrofitLogin(String url) {
        return new Retrofit.Builder()
                .baseUrl(url)
                .client(getHttpClient())
                .addConverterFactory(FastJsonConverterFactory.create())
                .build().create(WebRestApi.class);
    }
    private static OkHttpClient getHttpClient() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addNetworkInterceptor(logInterceptor);
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
                Request.Builder request = original.newBuilder();
                request.addHeader("Connection", "close")
                        .addHeader("Cache-Control", "no-cache");
                if (userInfo != null) {
                    request.addHeader("token", appToken == null ? "" : appToken)
                            .addHeader("userId", appId == null ? "" : appId);
                }
                return chain.proceed(request.method(original.method(), original.body())
                        .build());
            }
        });
        return httpClient.build();
    }
}

